<template>
  <div class="playWndWrapper">
    <div id="playWnd" class="playWnd"></div>
  </div>
</template>
  
<script setup>
import { onMounted, onUnmounted, reactive } from "vue";
const _props = defineProps({
  appkey: {
    type: String,
    default: "27576186",
  },
  ip: {
    type: String,
    default: "116.63.194.174",
  },
  secret: {
    type: String,
    default: "vhjcqyJV4n8jaVPu6pKf",
  },
  cameraIndexCode: {
    type: String,
    default: "e5d6bf643a624532850899b4fb69f3ac",
  },
  port: {
    type: String,
    default: "443",
  },
});

let oWebControl;
let bIE = !!window.ActiveXObject || "ActiveXObject" in window; // 是否为IE浏览器
let pubKey = ""; // demo中未使用加密，可根据需求参照开发指南自行使用加密功能
let initCount = 0;
let showDivInstruction = false; // 标志是否显示使用说明弹框

const _emit = defineEmits(["close"]);
const domSize = reactive({
  width: 800,
  height: 400,
});

const initParam = {
  argument: {
    appkey: _props.appkey,
    ip: _props.ip,
    port: _props.port,
    secret: _props.secret,
    enableHTTPS: 1,
    language: "zh_CN",
    layout: "1x1",
    playMode: 0, // 播放类型，0-预览，1-回放
    reconnectDuration: 5,
    reconnectTimes: 5,
    showSmart: 0, // 是否显示智能信息
    showToolbar: 0, // 是否显示工具栏
    toolBarButtonIDs:
      "2048,2049,2050,2304,2306,2305,2307,2308,2309,4096,4608,4097,4099,4098,4609,4100",
    buttonIDs: "0, 1, 16, 256, 257,258,259",
    snapDir: "D:/snap",
    videoDir: "D:/video",
  },
  funcName: "init",
};

const playParam = {
  argument: {
    authUuid: "",
    cameraIndexCode: _props.cameraIndexCode,
    ezvizDirect: 0,
    gpuMode: 0,
    streamMode: 0,
    transMode: 1,
    wndId: 1,
    cascade: 1,
  },
  funcName: "startPreview",
};

const layoutParam = {
  argument: {
    layout: "1x1",
  },
  funcName: "setLayout",
};

function onPlay() {
  requestInterface();
}

// value为字符串，JS_RequestInterface仅接收json格式的变量，且需要先解析出argument，并且将argument字段的内容转为字符串
function requestInterface() {
  const JsonParam = {
    argument: JSON.stringify(playParam.argument),
    funcName: playParam.funcName,
  };

  oWebControl.JS_RequestInterface(JsonParam).then(function (oData) {
    console.log((JSON.stringify(oData ? oData.responseMsg : ""), "play"));
  });
}

onMounted(() => {
  const JsonParam = {
    argument: JSON.stringify(initParam.argument),
    funcName: initParam.funcName,
  };
  initPlugin(function () {
    oWebControl.JS_RequestInterface(JsonParam).then(function (oData) {
      console.log(oData ? oData.responseMsg : "");
      oWebControl.JS_Resize(domSize.width, domSize.height); //
      onPlay();
    });
  });
});

function initPlugin(successCallBack = () => {}) {
  oWebControl = new WebControl({
    szPluginContainer: "playWnd",
    iServicePortStart: 15900,
    iServicePortEnd: 15900,
    szClassId: "23BF3B0A-2C56-4D97-9C03-0CB103AA8F11", // 用于IE10使用ActiveX的clsid
    cbConnectSuccess: function () {
      initCount = 0;
      setCallbacks();
      oWebControl
        .JS_StartService("window", {
          dllPath: "./VideoPluginConnect.dll",
        })
        .then(
          function () {
            oWebControl
              .JS_CreateWnd("playWnd", domSize.width, domSize.height)
              .then(function () {
                console.log("JS_CreateWnd success");
                oWebControl
                  .JS_RequestInterface({
                    funcName: "getRSAPubKey",
                    argument: JSON.stringify({
                      keyLength: 1024,
                    }),
                  })
                  .then(function (oData) {
                    console.log(oData);
                    if (oData.responseMsg.data) {
                      pubKey = oData.responseMsg.data;
                    }
                    successCallBack();
                  });
              });
          },
          function () {}
        );
    },
    cbConnectError: function () {
      console.log("cbConnectError");
      oWebControl = null;
      $("#playWnd").html("插件未启动，正在尝试启动，请稍候...");
      WebControl.JS_WakeUp("VideoWebPlugin://");
      initCount++;
      if (initCount < 3) {
        setTimeout(function () {
          initPlugin();
        }, 3000);
      } else {
        $("#playWnd").html("插件启动失败，请检查插件是否安装！");
      }
    },
    cbConnectClose: function (bNormalClose) {
      // 异常断开：bNormalClose = false
      // JS_Disconnect正常断开：bNormalClose = true
      console.log("cbConnectClose");
      oWebControl = null;
      $("#playWnd").html("插件未启动，正在尝试启动，请稍候...");
      WebControl.JS_WakeUp("VideoWebPlugin://");
      initCount++;
      if (initCount < 3) {
        setTimeout(function () {
          initPlugin();
        }, 3000);
      } else {
        $("#playWnd").html("插件启动失败，请检查插件是否安装！");
      }
    },
  });
}

// 格式化时间
function dateFormat(oDate, fmt) {
  var o = {
    "M+": oDate.getMonth() + 1, //月份
    "d+": oDate.getDate(), //日
    "h+": oDate.getHours(), //小时
    "m+": oDate.getMinutes(), //分
    "s+": oDate.getSeconds(), //秒
    "q+": Math.floor((oDate.getMonth() + 3) / 3), //季度
    S: oDate.getMilliseconds(), //毫秒
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (oDate.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
    }
  }
  return fmt;
}

// 设置窗口控制回调
function setCallbacks() {
  oWebControl.JS_SetWindowControlCallback({
    cbIntegrationCallBack: cbIntegrationCallBack,
  });
}

// 推送消息
function cbIntegrationCallBack(oData) {
  const responseMsg = oData.responseMsg;
  if (responseMsg.msg.result == 816) {
    // onHide()
    close();
  }

  console.log(responseMsg, "推送消息");
}

function close() {
  oWebControl.JS_DestroyWnd();
  _emit("close");
  window.removeEventListener("resize", resize);
}

function onHide() {
  oWebControl.JS_HideWnd();
}

function onShow() {
  oWebControl.JS_ShowWnd();
}

window.addEventListener("resize", resize);

function resize() {
  oWebControl.JS_Resize(domSize.width, domSize.height);
}

defineExpose({
  close
});
</script>
  
<style>
.playWndWrapper {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 800px;
  height: 400px;
}
.playWnd {
  width: 100%;
  height: 100%;
  z-index: 0;
}
</style>